<template>
  <div class="user-center-page">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧：个人信息展示 -->
      <div class="left-panel">
        <div class="info-card">
          <div class="card-header">
            <h2>个人信息</h2>
          </div>
          <div class="card-body">
            <!-- 头像区域：修复src绑定+加key确保更新 -->
            <div class="avatar-section">
              <div class="avatar-container">
                <a-upload
                  action="/api/upload/file"
                  :before-upload="beforeUpload"
                  :custom-request="handleUpload"
                  :file-list="[]"
                  :show-upload-list="false"
                >
                  <!-- 头像src绑定到editForm（上传后实时更新）+ key触发重新渲染 -->
                  <a-avatar :size="120" :src="editForm.userAvatar" :key="editForm.userAvatar">
                    <span v-if="!editForm.userAvatar" class="default-avatar-text">
                      {{ loginUserStore.loginUser.userName?.slice(0, 2) || '用户' }}
                    </span>
                  </a-avatar>
                  <div class="avatar-overlay">
                    <span class="upload-icon">📷</span>
                    <span class="upload-text">更换头像</span>
                  </div>
                </a-upload>
              </div>
            </div>

            <!-- 用户基本信息：修复时间格式化的数据源 -->
            <div class="user-details">
              <div class="detail-item">
                <span class="detail-label">用户账号</span>
                <span class="detail-value">{{ loginUserStore.loginUser.userName }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">用户角色</span>
                <a-tag
                  style="width: 50px; height: 25px; text-align: center; line-height: 25px"
                  color="cyan"
                  v-if="loginUserStore.loginUser.userRole === 'admin'"
                  >管理员</a-tag
                >
                <a-tag color="cyan" v-else>普通用户</a-tag>
              </div>
              <div class="detail-item">
                <span class="detail-label">注册时间</span>
                <span class="detail-value">{{
                  dayjs(loginUserStore.loginUser.createTime).format('YYYY-MM-DD HH:mm:ss')
                }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">最后更新</span>
                <span class="detail-value">{{
                  dayjs(loginUserStore.loginUser.updateTime).format('YYYY-MM-DD HH:mm:ss')
                }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：编辑区域 -->
      <div class="right-panel">
        <div class="edit-card">
          <div class="card-header">
            <h2>编辑个人信息</h2>
            <div class="save-status" v-if="formChanged">
              <span class="status-dot"></span>
              <span class="status-text">有未保存的更改</span>
            </div>
          </div>
          <div class="card-body">
            <form class="edit-form" @submit.prevent="handleSave">
              <!-- 昵称编辑 -->
              <div class="form-group">
                <label class="form-label">
                  <span class="label-text">用户昵称</span>
                  <span class="required-indicator">●</span>
                </label>
                <div class="input-container">
                  <input
                    type="text"
                    v-model="editForm.userName"
                    class="form-input"
                    placeholder="请输入昵称"
                    maxlength="20"
                    :class="{ 'input-empty': !editForm.userName.trim() }"
                  />
                  <div class="input-footer">
                    <span class="char-count">{{ editForm.userName.length }}/20</span>
                  </div>
                </div>
              </div>

              <!-- 简介编辑 -->
              <div class="form-group">
                <label class="form-label">
                  <span class="label-text">个人简介</span>
                </label>
                <div class="input-container">
                  <textarea
                    v-model="editForm.userProfile"
                    class="form-textarea"
                    placeholder="请输入个人简介（可选）"
                    maxlength="200"
                    rows="4"
                  ></textarea>
                  <div class="input-footer">
                    <span class="char-count">{{ editForm.userProfile.length }}/200</span>
                  </div>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="form-actions">
                <button
                  type="submit"
                  class="primary-btn"
                  :disabled="!formChanged || saving"
                  :class="{ loading: saving }"
                >
                  <span class="btn-spinner" v-if="saving"></span>
                  <span class="btn-text">{{ saving ? '保存中...' : '保存更改' }}</span>
                </button>
                <button
                  type="button"
                  class="secondary-btn"
                  @click="handleReset"
                  :disabled="!formChanged"
                >
                  重置
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// 1. 导入必要依赖（补充UploadProps类型，避免TS报错）
import { uploadFileUsingPost } from '@/api/fileController'
import { updateMyUserUsingPost } from '@/api/userController'
import { useLoginUserStore } from '@/stores/user'
import { message } from 'ant-design-vue'
import { UploadProps } from 'ant-design-vue/es/upload/interface'
import dayjs from 'dayjs'
import { computed, reactive, ref } from 'vue'

const loginUserStore = useLoginUserStore()
const loading = ref(false)
const saving = ref(false)

const editForm = reactive<API.UserVO>({
  userName: loginUserStore.loginUser.userName || '',
  userProfile: loginUserStore.loginUser.userProfile || '',
  userAvatar: loginUserStore.loginUser.userAvatar || '',
  userId: loginUserStore.loginUser.userId || '',
})

const originalFormData = ref<API.UserVO>({ ...editForm })

const formChanged = computed(() => {
  return (
    editForm.userName !== originalFormData.value.userName ||
    editForm.userProfile !== originalFormData.value.userProfile ||
    editForm.userAvatar !== originalFormData.value.userAvatar
  )
})

const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('不支持上传该格式的图片，推荐 JPG/PNG 格式!')
    return false
  }

  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('不能上传超过 2MB 的图片!')
    return false
  }

  return true
}

const handleUpload = async ({ file }: any) => {
  loading.value = true
  try {
    const res = await uploadFileUsingPost({}, file)
    console.log('上传接口返回:', res)

    if (res.data.code === 0 && res.data.data?.url) {
      editForm.userAvatar = res.data.data.url
      originalFormData.value = { ...editForm }
      message.success('头像上传成功,请保存信息')
    } else {
      message.error(`图片上传失败：${res.data.message || '接口无返回信息'}`)
    }
  } catch (error) {
    console.error('上传错误详情:', error) // 打印错误栈，方便排查
    message.error('图片上传失败，请查看控制台错误信息')
  } finally {
    loading.value = false
  }
}

const handleSave = async () => {
  try {
    saving.value = true
    const res = await updateMyUserUsingPost(editForm)
    console.log('保存接口返回:', res)

    if (res.data.code === 0) {
      loginUserStore.loginUser = { ...loginUserStore.loginUser, ...editForm }
      originalFormData.value = { ...editForm }
      message.success('个人信息更新成功')
    } else {
      message.error(`保存失败：${res.data.message || '接口无返回信息'}`)
    }
  } catch (error) {
    console.error('保存错误详情:', error)
    message.error('保存失败，请查看控制台错误信息')
  } finally {
    saving.value = false
  }
}

// 重置表单
const handleReset = () => {
  Object.keys(editForm).forEach((key) => {
    editForm[key] = originalFormData.value[key] || ''
  })
}
//获取实时
</script>

<style scoped>
/* 基础样式重置与全局设置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.user-center-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  font-family:
    -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

/* 主要内容区布局 */
.main-content {
  flex: 1;
  display: flex;
  gap: 24px;
  overflow: auto;
  margin: 0 auto;
  width: 100%;
  max-width: 1400px;
}

.left-panel {
  flex: 0 0 380px;
}

.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 卡片通用样式 */
.info-card,
.edit-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
  background: white;
  height: 100%;
  display: flex;
  flex-direction: column;
  transition:
    box-shadow 0.3s ease,
    transform 0.2s ease;
}

.info-card:hover,
.edit-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05);
  transform: translateY(-2px);
}

/* 卡片头部 */
.card-header {
  padding: 20px 28px;
  border-bottom: 1px solid #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

/* 未保存提示 */
.save-status {
  display: flex;
  align-items: center;
  gap: 8px;
  animation: shake 2s infinite ease-in-out;
}

@keyframes shake {
  0%,
  100% {
    transform: translateX(0);
  }
  25% {
    transform: translateX(-2px);
  }
  75% {
    transform: translateX(2px);
  }
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ff4d4f;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.6;
    transform: scale(1.1);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

.status-text {
  font-size: 13px;
  color: #ff4d4f;
  font-weight: 500;
}

/* 卡片内容区 */
.card-body {
  padding: 28px;
  flex: 1;
}

/* 头像区域样式 */
.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 32px;
}

.avatar-container {
  position: relative;
  width: 130px;
  height: 130px;
  border-radius: 50%;
  overflow: hidden;
  border: 4px solid #f9fafb;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  cursor: pointer;
}

/* 头像默认文本样式 */
.default-avatar-text {
  font-size: 24px;
  color: #666;
}

/* 头像hover提示层 */
.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(180deg, rgba(0, 0, 0, 0.2) 0%, rgba(0, 0, 0, 0.6) 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.4s ease;
  backdrop-filter: blur(2px);
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.upload-icon {
  font-size: 26px;
  margin-bottom: 6px;
}

.upload-text {
  font-size: 13px;
  font-weight: 500;
  letter-spacing: 0.5px;
}

/* 用户详情列表 */
.user-details {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #f5f5f5;
}

.detail-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.detail-label {
  font-weight: 500;
  color: #6b7280;
  min-width: 90px;
  font-size: 14px;
}

.detail-value {
  font-size: 15px;
  color: #1f2937;
  font-weight: 400;
}

/* 编辑表单样式 */
.edit-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.form-label {
  font-weight: 500;
  color: #1f2937;
  font-size: 15px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.required-indicator {
  color: #ff4d4f;
  font-size: 12px;
  line-height: 1;
}

.input-container {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-input,
.form-textarea {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 12px 16px;
  font-size: 15px;
  transition: all 0.3s ease;
  color: #1f2937;
  background-color: #fafafa;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
  background-color: white;
}

.form-input.input-empty {
  border-color: #f87171;
}

.form-textarea {
  resize: vertical;
  min-height: 100px;
  line-height: 1.6;
}

.input-footer {
  display: flex;
  justify-content: flex-end;
}

.char-count {
  font-size: 13px;
  color: #9ca3af;
}

/* 表单按钮样式 */
.form-actions {
  display: flex;
  gap: 16px;
  margin-top: 12px;
}

.primary-btn,
.secondary-btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-weight: 500;
}

.primary-btn {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

.primary-btn:hover:not(:disabled) {
  background-color: #40a9ff;
  border-color: #40a9ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
}

.primary-btn:disabled {
  background-color: #e6f7ff;
  border-color: #bae0ff;
  color: #91c9ff;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.secondary-btn {
  background-color: white;
  color: #1f2937;
  border-color: #e5e7eb;
}

.secondary-btn:hover:not(:disabled) {
  color: #1890ff;
  border-color: #1890ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.08);
}

.secondary-btn:disabled {
  color: #d1d5db;
  border-color: #e5e7eb;
  cursor: not-allowed;
}

/* 加载动画 */
.btn-spinner {
  width: 18px;
  height: 18px;
  border: 2px solid transparent;
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 响应式适配 */
@media (max-width: 992px) {
  .main-content {
    flex-direction: column;
    padding: 20px;
    gap: 20px;
  }

  .left-panel,
  .right-panel {
    flex: none;
    width: 100%;
  }

  .card-header {
    padding: 18px 24px;
  }

  .card-body {
    padding: 24px;
  }
}

@media (max-width: 576px) {
  .main-content {
    padding: 16px;
  }

  .form-actions {
    flex-direction: column;
    gap: 12px;
  }

  .primary-btn,
  .secondary-btn {
    width: 100%;
    padding: 12px;
  }

  .avatar-container {
    width: 110px;
    height: 110px;
  }

  .user-details {
    gap: 16px;
  }

  .detail-item {
    padding-bottom: 12px;
  }
}
</style>
